<template>
  <div class="login-container">
    <el-form @submit.prevent="login">
      <h1 align="center">个人网盘📁</h1>
      <el-form-item label="Email">
        <el-input v-model="email" placeholder="Enter your email"></el-input>
      </el-form-item>
      <el-form-item label="Password">
        <el-input v-model="password" type="password" placeholder="Enter your password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">Login</el-button>
        <el-button type="text" @click="goToRegister">Register</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'Login',
  setup() {
    const router = useRouter()
    const email = ref('')
    const password = ref('')

    const login = async () => {
      try {
        const response = await axios.post('/login', {
          email: email.value,
          password: password.value
        })
        if (response.data.message === 'success') {
          ElMessage.success('Login successful')
          localStorage.setItem('accessToken', response.data.access_token)
          await router.push('/')
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('An error occurred during login')
      }
    }

    const goToRegister = () => {
      router.push('/register')
    }

    return {
      email,
      password,
      login,
      goToRegister
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.el-form {
  width: 300px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>